<!-- 生产设置->物料清单 -->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col v-if="permissions.includes('bom:add')" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="newProcess">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col v-if="permissions.includes('bom:edit')" :class="editMask&&voucherState != 1?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="editMask&&voucherState != 1?editClick():''">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">修改</div>
                            </div>
                        </a-col>
                        <a-col v-if="permissions.includes('bom:delete')" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="removeData">
                                <a-icon class="btns-icon" type="delete" />
                                <div class="btns-text">删除</div>
                            </div>
                        </a-col>
                        <a-col v-if="permissions.includes('bom:save')" :class="editMask?'btns-disable':''" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="editMask?'':submit()">
                                <a-icon class="btns-icon" type="save" />
                                <div class="btns-text">保存</div>
                            </div>
                        </a-col>
                        <a-col v-if="permissions.includes('bom:examine')" :class="orderId && editMask &&voucherState == 0?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="orderId && editMask && voucherState == 0?auditClick(1):''">
                                <a-icon class="btns-icon" type="audit" />
                                <div class="btns-text">审核</div>
                            </div>
                        </a-col>
                        <a-col v-if="permissions.includes('bom:examine')" :class="orderId && editMask &&voucherState == 1?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="orderId && editMask && voucherState == 1?auditClick(0):''">
                                <a-icon class="btns-icon" type="audit" />
                                <div class="btns-text">弃审</div>
                            </div>
                        </a-col>
                        <a-col :class="editMask?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="editMask?copy():''">
                                <a-icon class="btns-icon" type="copy" />
                                <div class="btns-text">复制</div>
                            </div>
                        </a-col>
                        <a-col :class="!editMask?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="()=>{editMask = true}">
                                <a-icon class="btns-icon" type="undo" />
                                <div class="btns-text">撤销</div>
                            </div>
                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="getBomGroupList">
                                <a-icon class="btns-icon" type="sync" />
                                <div class="btns-text">刷新</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <div ref="print" class="credentials-bom-wrapper-bb" id="documents-wrapper">
                <h3 class="text-center">
                    <span class="text-name">物料清单</span><br>
                </h3>
                <a-row style="border:1px solid #ddd;">
                    <a-col :span="4">
                        <section class="tabbl-bom">
                            <!-- :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" -->
                            <!-- <a-table id="route_tb" :columns="columnsList" :data-source="listData" :customRow="customTable" bordered :scroll="{x:500,y:400}" :rowClassName="rowClassName" :pagination="false">
                                <div slot="filterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" style="padding: 8px">
                                    <a-input v-ant-ref="c => (searchInput = c)" :placeholder="`搜索${column.title}`" v-model="searchInventoryCode" style="width: 188px; margin-bottom: 8px; display: block;" @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)" />
                                    <a-button type="primary" icon="search" size="small" style="width: 90px; margin-right: 8px" @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)">
                                        搜索
                                    </a-button>
                                    <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
                                        重置
                                    </a-button>
                                </div>
                                <a-icon slot="filterIcon" type="filter" theme="filled" :style="{ color: '#444' }" />
                            </a-table> -->
                        </section>

                        <div class="bom-tree-wrapper">

                            <div class="tree-box not-copy" style="height:99%">
                                <a-input-search style="margin-bottom: 8px" placeholder="搜索标题" @change="onTreeSearchChange" />
                                <a-tree show-line default-expand-all :treeData="typsTreeData" v-if="typsTreeData.length>0 && isShowTree" :selectedKeys="defaultSelectedKeys" @select="onSelect" :replaceFields="replaceFields">
                                    <a-icon slot="switcherIcon" type="down" />
                                </a-tree>
                            </div>
                        </div>
                    </a-col>
                    <a-col :span="20" style="min-height:366px;padding:10px;">

                        <section>
                            <div><span class="audit-status" style="z-index:78" v-show="voucherState==1">已审</span></div>
                            <a-form-model :layout="formLayout">
                                <div class="header-box" style="position:relative">
                                    <!-- 遮罩（点击修改关闭遮罩） -->
                                    <div class="edit-mask-route" v-show="editMask"></div>
                                    <a-row class="order-dynamic-form-wrapper">

                                        <!-- <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="BOM用途">
                                                <a-input v-model="dataJson.bomUse"></a-input>
                                            </a-form-model-item>
                                        </a-col> -->
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="母件编码" :rules="[{ required: true, message:'',trigger:'input'}]">
                                                <a-input v-model="dataJson.inventoryCode" onkeyup="value=value.replace(/[^\d]/g,'')" @change="handleArchiveChange(1)" @click="handlInputArchives()" style="position:relative;z-index:50"></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="母件名称" :rules="[{ required: true, message:'',trigger:'input'}]">
                                                <a-input v-model="dataJson.inventoryName" @change="handleArchiveChange(2)" @click="handlInputArchives()" style="position:relative;z-index:50"></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="分组" :rules="[{ required: true, message:'',trigger:'input'}]">
                                                <a-select v-model="dataJson.bomGroupId" v-if="typsTreeData[0]">
                                                    <a-select-option v-for="item in typsTreeData[0].children" :key="item" :value="item.id">
                                                        {{item.name}}
                                                    </a-select-option>
                                                </a-select>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="BOM类型">
                                                <a-select v-model="dataJson.bomType">
                                                    <a-select-option :value="2" label="">
                                                        生产
                                                    </a-select-option>
                                                    <a-select-option :value="3" label="">
                                                        成本
                                                    </a-select-option>
                                                    <a-select-option :value="4" label="">
                                                        维修
                                                    </a-select-option>
                                                    <a-select-option :value="1" label="">
                                                        工程
                                                    </a-select-option>
                                                    <a-select-option :value="5" label="">
                                                        销售
                                                    </a-select-option>
                                                </a-select>
                                            </a-form-model-item>
                                        </a-col>
                                        <!-- <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="BOM编码">
                                                <a-input v-model="dataJson.cost"></a-input>
                                            </a-form-model-item>
                                        </a-col> -->
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="工程图号">
                                                <a-input v-model="dataJson.bomEdCode"></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="规格型号">
                                                <a-input v-model="dataJson.specification" disabled></a-input>
                                            </a-form-model-item>
                                        </a-col>

                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="计量单位">
                                                <a-input v-model="dataJson.unitName" disabled></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="工艺路线" :rules="[{ required: true, message:'',trigger:'input'}]">
                                                <a-input v-model="dataJson.processRouteName" @click="searchGroup(1)" @change="searchGroup(2)" :style="styleProcess"></a-input>
                                                <searchGroupHeader ref="processSearch" :inputValue="dataJson.processRouteName" :componentName="'processRoute'" @clickItem="searchBackData"></searchGroupHeader>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="默认数量">
                                                <a-input v-model="dataJson.produceQuantity" disabled></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="成品率(%)" :rules="[{ required: true, message:'',trigger:'input'}]">
                                                <a-input v-model="dataJson.finishProductRate" :value="100"></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <!-- <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="成本">
                                                <a-input v-model="dataJson.cost"></a-input>
                                            </a-form-model-item>
                                        </a-col> -->
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="版本说明">
                                                <a-input v-model="dataJson.remarks"></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="版本号" :rules="[{ required: true, message:'',trigger:'input'}]">
                                                <a-input v-model="dataJson.versionCode"></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="版本日期">
                                                <a-date-picker v-model="dataJson.versionDate" @change="onChangeDate" />
                                            </a-form-model-item>
                                        </a-col>
                                    </a-row>
                                </div>
                                <div class="table-box">
                                    <!--修改状态的表格-->
                                    <a-table id="editBom_tb" v-if="!editMask" class="atable-edit" :columns="columns" :customRow="customClick" :data-source="dataSource" :pagination="false" bordered :scroll="{x:1000,y:300}">
                                        <template v-for="item in editColumnArraya" :slot="item" slot-scope="text, record ,index">
                                            <div>
                                                <editable-cell v-if="isRouterAlive" :record="record" :checkType="checkType" :col="item" :text="text" :unitsAssistSelect="unitsAssistSelect" :unitsDataDetails="unitsDataDetails" @change="onCellChange(index, item, $event)" @choiceAddData="choiceAddData(index,$event)" />
                                            </div>
                                        </template>
                                    </a-table>
                                    <!--查看状态的表格-->
                                    <a-table id="lookBom_tb" class="look-table" v-if="editMask" indentSize="18" :columns="columns" :data-source="innerData" :pagination="false" bordered :scroll="{x:1000,y:300}" @expand="expandChange">
                                        <!--发料方式-->
                                        <template slot="deliveryMethod" slot-scope="text">
                                            <div>{{ text == 1?'直接领料':text == 2?'调拨领料':text==3?'直接倒冲':text==4?'调拨倒冲':text==5?'不发料':'' }}</div>
                                        </template>
                                        <!--供应类型-->
                                        <template slot="supplyType" slot-scope="text">
                                            <div>{{ text == 1?'采购':text == 2?'自制':text==3?'委外':'' }}</div>
                                        </template>
                                    </a-table>
                                </div>
                                <div class="footer-box">
                                    <a-row class="order-dynamic-form-wrapper">
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="修改人">
                                                <a-input v-model="dataJson.updateUserName" :disabled="true" />
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="修改时间">
                                                <a-input v-model="dataJson.updateDate" :disabled="true" />
                                            </a-form-model-item>
                                        </a-col>
                                        <!-- <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="备注">
                                                <a-input v-model="dataJson.remarks" :disabled="true" />
                                            </a-form-model-item>
                                        </a-col> -->
                                        <!-- <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="状态">
                                                {{dataJson.status=0?'停用':'正常'}}
                                            </a-form-model-item>
                                        </a-col> -->
                                    </a-row>
                                </div>
                            </a-form-model>

                            <searchArchives v-if="maskArchives" ref="searchArchivesRef" :inventoryDomTop="inventoryDomTop" :inventoryDomRight="inventoryDomRight" :inputType="1" :checkType="checkHeadType" :inputVal="inputVal" @closeArchives="closeArchives" @check="checkArchives"></searchArchives>
                            <div class="mask-archives" v-show="maskArchives" @click="closeArchives"></div>
                        </section>
                    </a-col>
                </a-row>

            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!--  <li @click="handleCopy()">复制行</li> -->

                </ul>
            </div>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <div v-html="stylePrint"></div>
    </div>
</template>
<script>

import { mapState } from "vuex";
import { pageList } from "@/api/inventory/unit";//计量单位
import editableCell from "./workshop/editTable/EditableCell"
import { save, list, remove, details, examine, groupList } from "@/api/production/bom";
import searchArchives from '@/components/OrderDynamicForm/searchArchives';
import { Controlwidth } from "@/utils/antTableComponents";
import { classPageListToTree, searchInTreeData } from "@/utils/tree";

import searchGroupDetail from "@/components/PopUpLayer/searchGroupDetail";  //静态表格明细搜索组
import searchGroupHeader from "@/components/PopUpLayer/searchGroupHeader";

export default {
    components: {
        editableCell,
        searchArchives,
        searchGroupDetail,
        searchGroupHeader,
    },
    data () {
        return {
            //----------↓样式----------
            fromStyle: { paddingTop: "8px" },
            labelCol: { span: 10 },
            wrapperCol: { span: 14 },
            editFalse: {
                borderBottom: '1px solid #ded7d7'
            },
            grid: {
                xs: 24,
                sm: 24,
                md: 12,
                lg: 8,
                xl: 8,
                xxl: 6
            },
            btn_grid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------
            setTime: null,  //延迟请求
            checkType: 'is_material,is_invented_key',//生产耗用，虚拟件
            checkHeadType: 'is_made_self,is_made_request,is_invented_key',//自制，委外，虚拟件
            replaceFields: {
                // tree 别名
                title: "showname",
                key: "key",
            },
            editMask: false,
            dataSource: [],
            innerData: [],
            isRouterAlive: true,
            dragStartObj: null,     //拖动的目标
            dragEndObj: null,       //目标位置
            dragStartIndex: null,
            dragEndIndex: null,
            customClick: (record, index) => {
                return {
                    on: {
                        contextmenu: (e) => {//右键事件
                            e.preventDefault();
                            if (index <= this.dataSource.length) {
                                this.openMenu(e);
                                console.log('右键点击的', index);
                                this.thisClickId = index;
                                // this.thisClickRecord = record;
                            }
                        },
                        click: (e) => {
                            e.preventDefault();
                            if (record.unitGroupId) {
                                this.unitsAssistSelect = [];
                                this.unitsDataDetails.forEach((element, index) => {
                                    if (element.unitGroupId == record.unitGroupId && !element.isMainUnit) {//&& !element.isMainUnit
                                        this.unitsAssistSelect.push(element);
                                    }
                                });
                            } else {
                                this.unitsAssistSelect = [];
                            }
                        }
                    }
                }
            },
            customTable: (record, index) => {
                return {
                    on: {
                        click: (e) => {
                            this.mouseIndex = record.key;
                            this.orderId = record.id;
                            this.voucherState = record.voucherState;
                            this.nowRecord = record;

                            console.log(record);
                            this.getDetails(record);
                            // this.$router.push('/production/bomMaintain?id=' + record.id);
                        }
                    }
                }
            },
            listData: [],
            mouseIndex: null,
            orderId: null,
            nowRecord: {},
            voucherState: 0,
            columnsList: [
                 {
                title: '版本号',
                dataIndex: 'versionCode',
                ellipsis: true,
                width: 100
                },
                {
                title: 'BOM类型',
                dataIndex: 'bomType',
                ellipsis: true,
                customRender: (text, row, index) => {
                    return <span>{text == 1 ? '工程' : text == 2 ? '生产' : text == 3 ? '成本' : text == 4 ? '维修' : text == 5 ? '销售' : ''}</span>;
                },
                width: 80,
            }, {
                title: '母件编码',
                dataIndex: 'inventoryCode',
                sorter: (a, b) => a.inventoryCode.length - b.inventoryCode.length,
                ellipsis: true,
                scopedSlots: {
                    filterDropdown: 'filterDropdown',
                    filterIcon: 'filterIcon',
                },
                width: 100
            }, {
                title: '母件名称',
                dataIndex: 'inventoryName',
                sorter: (a, b) => a.inventoryName.length - b.inventoryName.length,
                ellipsis: true,
                scopedSlots: {
                    filterDropdown: 'filterDropdown',
                    filterIcon: 'filterIcon',
                },
                width: 120
            }, {
                title: '规格型号',
                dataIndex: 'specification',
                ellipsis: true,
                width: 80
            },],
            columns: [
                {
                    title: '序号',
                    width: 40,
                    align: 'center',
                    customRender: (text, row, index) => {
                        return <span>{index + 1}</span>;
                    }
                },
                {
                    title: <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span> 子件编码</div>,
                    dataIndex: 'inventoryCode',
                    width: 120,
                    scopedSlots: { customRender: 'inventoryCode' },
                    ellipsis: true,
                }, {
                    title: <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span> 子件名称</div>,
                    dataIndex: 'inventoryName',
                    width: 120,
                    scopedSlots: { customRender: 'inventoryName' },
                    ellipsis: true,
                }, {
                    title: '规格型号',
                    dataIndex: 'specification',
                    width: 100,
                    scopedSlots: { customRender: 'specification' },
                    ellipsis: true,
                }, {
                    title: '主计量',
                    dataIndex: 'baseUnitName',
                    width: 100,
                    ellipsis: true,
                }, {
                    title: <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span> 主计量数量</div>,
                    dataIndex: 'requireQuantity',
                    width: 100,
                    scopedSlots: { customRender: 'requireQuantity' },
                    ellipsis: true,
                }, {
                    title: '辅计量',
                    dataIndex: 'subUnitName',
                    width: 100,
                    scopedSlots: { customRender: 'subUnitName' },
                    ellipsis: true,
                }, {
                    title: '辅计量数量',
                    dataIndex: 'subQuantity',
                    width: 100,
                    scopedSlots: { customRender: 'subQuantity' },
                    ellipsis: true,
                }, {
                    title: '换算率',
                    dataIndex: 'unitExchangeRate',
                    width: 80,
                    scopedSlots: { customRender: 'unitExchangeRate' },
                    ellipsis: true,
                },
                // {
                //     title: <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span> 标准用量</div>,
                //     dataIndex: 'requireQuantity',
                //     width: 100,
                //     scopedSlots: { customRender: 'requireQuantity' },
                //     align: 'right',
                //     ellipsis: true,
                // },
                {
                    title: '子件损耗率(%)',
                    dataIndex: 'lossRate',
                    width: 100,
                    scopedSlots: { customRender: 'lossRate' },
                    align: 'right',
                    ellipsis: true,
                }, {
                    title: '子件BOM',
                    dataIndex: 'bomVersion',
                    width: 100,
                    scopedSlots: { customRender: 'bomVersion' },
                    ellipsis: true,
                }, {
                    title: <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span> 供应类型</div>,//1:采购2:自制3:委外
                    dataIndex: 'supplyType',
                    width: 100,
                    scopedSlots: { customRender: 'supplyType' },
                    ellipsis: true,
                }, {
                    title: <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span> 发料方式</div>,//1:直接领料2:调拨领料3:直接倒冲4:调拨倒冲5:不发料
                    dataIndex: 'deliveryMethod',
                    width: 100,
                    scopedSlots: { customRender: 'deliveryMethod' },
                    ellipsis: true,
                }, {
                    title: '成本',
                    dataIndex: 'cost',
                    width: 60,
                    scopedSlots: { customRender: 'cost' },
                    ellipsis: true,
                }, {
                    title: '备注',
                    dataIndex: 'remarks',
                    width: 140,
                    scopedSlots: { customRender: 'remarks' },
                    ellipsis: true,
                }],
            visible: false,
            top: 0,
            left: 0,
            editColumnArraya: [],
            dataSourceNumber: 9,//默认渲染多少行表格数据
            dataJson: {
                bomLevel: null,//bom层级
                bomType: 2,//bom类型
                bomUse: null, //bom用途
                cost: null,//成本
                bomEdCode: null,//工程图号
                inventoryCode: null,//母件bom编码
                inventoryId: null,//母件bomid
                inventoryName: null,//母件bom名称
                officeId: null,//生产车间id
                officeName: null,//生产车间名称
                orderDetailList: [],//子bom明细

                unitId: null,//单计量Id
                unitName: null,//单计量名称
                unitGroupId: null,//多计量id

                unitExchangeRate: null,//换算率
                subQuantity: null,//需要数量(辅)
                subUnit: null,//辅计量
                subUnitName: null,//辅计量名称
                baseUnit: null,//主计量ID
                baseUnitName: null,//主计量名称
                requireQuantity: null,//需要数量(主)


                processRouteId: null,//工艺路线id
                processRouteName: null,//工艺路线名称
                produceQuantity: 1,//生产数量
                remarks: null,//备注
                specification: null,//规格型号
                versionCode: null,//版本号
                versionDate: null,//版本日期
                finishProductRate: 100,//成品率

                updateDate: null,
                bomGroupName: null,//bom分组
                bomGroupId: null,//bom分组
            },
            defaultSelectedKeys: [],//初始加载默认选中的bom

            //物料
            maskArchives: false,
            inventoryDomTop: null,
            inventoryDomRight: null,
            inputVal: null,
            selectedRowKeys: [],
            selectedData: [],
            childrenData: [],//子级数据
            recordId: null,//当前点击展开的id
            styleProcess: "{}",
            styleOffice: "{}",
            position: {},

            searchInventoryCode: null,//母件编码搜索
            unitsDataDetails: [],//多计量组
            unitsAssistSelect: [],

            treeData: [],//分组树形
            typsTreeData: [],
            isShowTree: true,
        };
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    created () {
        this.tableInit();//初始化表格
        this.editColumnArray(this.columns);
        this.getGrouplist();//多计量组
        this.getBomGroupList();//获取物料清单分组
    },
    updated () {
        Controlwidth("route_tb", 50);
        Controlwidth("editBom_tb", 80);
        Controlwidth("lookBom_tb", 80);
    },
    watch: {
        visible (value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenu);
            } else {
                document.body.removeEventListener("click", this.closeMenu);
            }
        },
    },
    methods: {
        tableInit () {
            for (let i = 0; i < this.dataSourceNumber; i++) {
                this.dataSource.push({})
            }
            this.reload();
            console.log(this.dataSource)
        },
        getBomGroupList () {
            //获取物料清单分组
            this.treeData = [];
            groupList().then(res => {
                if (res.code == 200) {
                    console.log("BOM_Tree数据01:", res.data);
                    this.treeData = res.data.map(r => {
                        return { ...r, key: r.id }
                    })

                    console.log("BOM_Tree数据02:", this.treeData);

                    this.treeFormate();
                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        treeFormate () {
            const childrenNav = [];
            classPageListToTree(this.treeData, childrenNav, 0);
            //添加showTitle处理后的data
            this.typsTreeData = [
                {
                    title: "所有BOM",
                    showname: "所有BOM",
                    key: "",
                    children: this.getTreeData(childrenNav)
                }
            ];
            // this.typsTreeData[0].children.unshift({
            //     title: '默认分组',
            //     name: '默认分组',
            //     showname: '默认分组',
            //     id: 930413,
            //     key: 930413,
            //     children: []
            // })
            this.getList();//获取BOM列表
        },
        //递归添加显示的tree title
        getTreeData (data) {
            for (let i = 0; i < data.length; i++) {
                let element = data[i];
                this.$set(element, "showname", `${element.name}`);
                if (element.children) {
                    this.getTreeData(element.children);
                }
            }
            return data;
        },
        reload () {
            //强制刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        reloadTree () {
            console.log("进入reloadTree");
            this.isShowTree = false;
            this.$nextTick(function () {
                this.isShowTree = true;
            });
        },
        //计量单位组下面的组单位
        getGrouplist () {
            let requestData = {
                current: 1,
                size: 1000,
                unitGroupId: -1
            }
            pageList(requestData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const { records } = data;
                    this.unitsDataDetails = records;
                }
            }).catch(error => { });
        },
        newProcess () {
            //新增（初始化数据）
            this.dataSource = [];
            this.mouseIndex = null;
            this.editMask = false;
            this.tableInit();
            this.dataJson = {
                bomType: 1,
                finishProductRate: 100,//成品率
            };
            this.orderId = null;
            this.voucherState = 0;
        },
        openMenu (e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.top = y;
            this.left = x;
            this.visible = true;
        },
        closeMenu () {
            //隐藏右键菜单
            this.visible = false;
        },
        handleAdd () {
            //新增数据
            const { count, dataSource } = this;
            const newData = {};
            this.$nextTick(() => {
                this.dataSource.splice(this.dataSource.length, 0, newData);
            })
            console.log('新增行：', this.dataSource)
        },
        handleDelete () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickId;
            console.log(numberId);
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk () {
                    let dataSource = [..._this.dataSource];
                    console.log(_this.dataSource.length);
                    if (dataSource.length - 1 > _this.dataSourceNumber) {
                        //大于规定行数(删除)
                        _this.dataSource = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = ""
                                    }
                                }
                            }
                        }
                        _this.dataSource = dataSource;
                    }


                    _this.reload();
                },
                onCancel () { },
            });
        },
        //根据计量组id返回 非主计量的 辅助计量组
        returnGroupUnits (id) {
            let elementId = null;
            let units = [];
            this.unitsDataDetails.forEach(element => {
                if (id == element.id) {
                    elementId = element.unitGroupId;
                }
            });
            this.unitsDataDetails.forEach(element => {
                if (elementId == element.unitGroupId) {// && !element.isMainUnit
                    units.push(element);
                }
            });
            return units;
        },
        onChangeDate (v, s) {
            this.dataJson.versionDate = s;
        },
        onCellChange (indexTable, dataIndex, value) {
            const dataSource = [...this.dataSource];
            const target = dataSource.find((item, index) => index === indexTable);
            console.log(target, dataIndex, value, indexTable);

            this.$set(target, dataIndex, value)
            if (dataIndex == 'workCode' || dataIndex == 'workName') {
                //工序编码
                if (value) {
                    target['workCode'] = value.code;
                    target['workId'] = value.id;
                    target['workName'] = value.name;
                    target['processMethod'] = value.processMethod;
                } else {
                    target['workCode'] = null;
                    target['workId'] = null;
                    target['workName'] = null;
                    target['processMethod'] = null;
                }

            } else if (dataIndex == 'inventoryCode' || dataIndex == 'inventoryName') {
                //子件编码
                if (value) {

                    //选取物料后重置当前列数据
                    for (const key in target) {
                        console.log(key);
                        target[key] = ''
                    }

                    target['inventoryCode'] = value.inventoryCode;
                    target['inventoryId'] = value.id;
                    target['inventoryName'] = value.inventoryName;
                    target['specification'] = value.inventorySpecification;


                    if (value.unitId) {//单计量
                        target['unitId'] = value.unitId;
                        target['unitName'] = value.unitName;

                        //主计量
                        target['baseUnit'] = value.unitId;
                        target['baseUnitName'] = value.unitName;
                    }

                    if (value.unitGroupId) {//多计量
                        target['unitGroupId'] = value.unitGroupId;
                        target['baseUnit'] = value.mainUnit;
                        target['baseUnitName'] = value.mainUnitName;


                        //辅助计量数据
                        this.unitsAssistSelect = [];
                        this.unitsDataDetails.forEach((element, index) => {
                            if (element.unitGroupId == value.unitGroupId && !element.isMainUnit) {//&& !element.isMainUnit
                                this.unitsAssistSelect.push(element);
                            }
                        });


                        //辅助计量设置默认值
                        this.unitsAssistSelect.forEach(item => {
                            if (value.proUnit == item.id) {//生产常用单位
                                target['subUnit'] = item.id;//辅计量
                                target['subUnitName'] = item.name;//辅计量名称
                                target['unitExchangeRate'] = item.changeRate;//换算率
                            }
                        });



                        console.log('辅助计量组：', this.unitsAssistSelect, this.unitsDataDetails);
                    }

                    target['lossRate'] = '0.00';

                    //置空当前子件数据
                    target['bomVersion'] = null;
                    target['bomId'] = null;
                    target['requireQuantity'] = null;
                    target['remarks'] = null;
                    target['supplyType'] = null;

                } else {
                    target['inventoryCode'] = null;
                    target['inventoryId'] = null;
                    target['inventoryName'] = null;
                    target['specification'] = null;
                    target['unitName'] = null;
                    target['unitId'] = null;
                    target['lossRate'] = null;
                }
            } else if (dataIndex == 'requireQuantity' || dataIndex == 'price' || dataIndex == 'includeTaxPrice' || dataIndex == 'taxRate' || dataIndex == 'unitExchangeRate' || dataIndex == 'subQuantity' || dataIndex == 'subUnitName') {
                /**
                * price:单价
                * includeTaxPrice:含税单价
                * requireQuantity:数量
                * taxRate：税率
                * amount:金额
                * includetaxAmount:含税金额
                * 
                * unitExchangeRate:换算率
                * subQuantity:辅计量数量
                * subUnitName:辅计量
                */
                if (target && value) {

                    //辅助计量改变的时候 换算率赋值后也要计算 dataIndex == 'subUnit'
                    if (dataIndex != 'subUnitName') {
                        target[dataIndex] = value;
                    } else {
                        console.log('辅计量选中的值---------', value)
                        //辅计量
                        target['subUnit'] = value.id;//辅计量
                        target['subUnitName'] = value.name;//辅计量名称
                        target['unitExchangeRate'] = value.unitExchangeRate;//换算率
                        target['convertType'] = value.convertType;//换算率是否浮动
                    }


                    //==========================换算率相关

                    //输入换算率的时候
                    if (dataIndex == 'unitExchangeRate' || value.unitExchangeRate) {
                        //辅计量必须选择
                        if (!target.subUnit || target.subUnit == null || target.subUnit == '' || !target.subQuantity) {
                            this.$message.warning('辅计量 和 辅计量数量 必须存在值');
                            return;
                        } else {
                            if (target.requireQuantity) {
                                target['subQuantity'] = '';
                                //辅计量数量=主计量数量 / 换算率
                                let n = Number(target.requireQuantity) / Number(target.unitExchangeRate);
                                target['subQuantity'] = n.toFixed(4);
                            }
                        }
                    }

                    //输入辅计量数量的时候
                    if (dataIndex == 'subQuantity') {
                        //辅计量必须选择
                        if (!target.subUnit || target.subUnit == null || target.subUnit == '') {
                            this.$message.error('辅计量必须选择');
                            return;
                        } else {
                            // if (target.requireQuantity) {
                            //     //换算率 = 主计量数量/辅计量数量
                            //     let n = Number(target.requireQuantity) / Number(target.subQuantity);
                            //     target['unitExchangeRate'] = n.toFixed(4);
                            // } else {
                            //主计量数量 = 辅计量数量*换算率
                            let n = Number(target.subQuantity) * Number(target.unitExchangeRate);
                            target['requireQuantity'] = n.toFixed(4);
                            // }
                        }
                    }
                    //输入数量的时候
                    if (dataIndex == 'requireQuantity') {
                        //输入数量  并且辅计量数量存在
                        if (target.unitExchangeRate) {
                            //辅计量数量 = 主计量数量*换算率
                            let total = Number(target.requireQuantity) / Number(target.unitExchangeRate);
                            target['subQuantity'] = total.toFixed(4);
                        }
                    }

                    //☆☆☆☆☆☆☆触发加工单物料数量的计算☆☆☆☆☆☆☆
                    // if (dataIndex == 'requireQuantity' || dataIndex == 'unitExchangeRate' || dataIndex == 'subQuantity')
                    // if (this.sourceCode == 'ProductionWork' && this.dataSourceBom) {//页面如果是加工单
                    //     if (this.dataSourceBom.length > 0) {//判断物料明细是否有数据
                    //         this.dataSourceBomNumber = Number(target.requireQuantity);
                    //         this.dataSourceBom.forEach(item => {
                    //             let num = Number(target.requireQuantity) * Number(item.baseRequireQuantity);
                    //             item.requireQuantity = num;
                    //         });
                    //     }
                    // }

                    //==========================换算率相关

                    //计算单价
                    if (dataIndex == 'includeTaxPrice') {
                        target['price'] = '';
                        if (target.includeTaxPrice && target.taxRate) {
                            let total = Number(target.includeTaxPrice) / (1 + target.taxRate / 100);
                            target['price'] = total.toFixed(2);
                        } else {
                            target['price'] = Number(target.includeTaxPrice);
                        }
                    }
                    //计算含税单价
                    if (dataIndex == 'price') {
                        target['includeTaxPrice'] = '';
                        if (target.price && target.taxRate) {
                            let total = Number(target.price) * (1 + target.taxRate / 100);
                            target['includeTaxPrice'] = total.toFixed(2);
                        } else {
                            target['includeTaxPrice'] = Number(target.price);
                        }
                    }

                    if (dataIndex == 'taxRate') {//输入税率的情况
                        if (!target.price && !target.includeTaxPrice) {//1.单价和含税单价都不存在
                            return;
                        } else {//两个都存在（以单价为准）
                            target['includeTaxPrice'] = '';//清空含税单价
                            if (target.price && target.taxRate) {
                                let total = Number(target.price) * (1 + target.taxRate / 100);
                                target['includeTaxPrice'] = total.toFixed(2);
                            } else {
                                target['includeTaxPrice'] = Number(target.price);
                            }
                        }
                    }

                    //算税额
                    if (target.requireQuantity && target.price && target.taxRate) {
                        //税率= 单价*数量*税率
                        let tax = Number(target.requireQuantity) * Number(target.price) * Number(target.taxRate) / 100
                        target['tax'] = tax.toFixed(4);
                    }

                    if (target.requireQuantity && target.price) {
                        //数量*单价=金额
                        let total = Number(target.requireQuantity) * Number(target.price);
                        target['amount'] = total.toFixed(2);
                    }

                    // if (target.requireQuantity && target.includeTaxPrice) {
                    //     //数量*含税单价=含税金额
                    //     let total = Number(target.requireQuantity) * Number(target.includeTaxPrice);
                    //     target['includeTaxAmount'] = total.toFixed(2);
                    // }

                    if (target.amount && target.tax) {
                        //含税金额 = 金额 + 税额
                        let total = Number(target.amount) + Number(target.tax);
                        target['includeTaxAmount'] = total.toFixed(2);
                    }


                    this.$nextTick(() => {
                        this.dataSource = dataSource;
                        this.reload();
                    })
                }
            } else if (dataIndex == 'bomVersion') {
                //查询下级bom(子件bom)
                if (value) {
                    target['bomVersion'] = value.versionCode;
                    target['bomId'] = value.id;
                } else {
                    target['bomVersion'] = null;
                    target['bomId'] = null;
                }
            }

            this.$nextTick(() => {
                this.dataSource = dataSource;
                console.log('明细数据：', this.dataSource)
                this.reload();
            })

        },

        //获取可编辑的列名
        editColumnArray (column) {
            let editcloumn = [];
            column.forEach((item, index) => {
                editcloumn.push(item.dataIndex);
            });
            this.editColumnArraya = editcloumn;
        },
        onSelect (keys, event) {
            this.selectedKeys = keys;
            this.defaultSelectedKeys = keys;
            // 点击树节点触发
            this.selectedRows = event.node.dataRef;

            console.log(this.selectedKeys, this.selectedRows);
            // this.mouseIndex = record.key;

            this.orderId = this.selectedRows.id;
            this.voucherState = this.selectedRows.voucherState;
            this.nowRecord = this.selectedRows;

            this.getDetails(this.selectedRows);
        },
        //列表
        getList (searchArray) {
            let postData = {
                "current": 1,
                "size": '-1'
            }
            if (searchArray) {
                if (Object.keys(searchArray).length > 0) {
                    postData = Object.assign(postData, searchArray);
                }
            }

            list(postData).then(response => {
                if (response.code === 200) {
                    const { records } = response.data;

                    if (records.length > 0) {
                        records.forEach(item => {
                            item.key = item.id;
                            item.showname = `(${item.inventoryCode})${item.inventoryName}/${item.specification}/${item.versionCode}`;
                        });
                        this.defaultSelectedKeys = [records[0].key];//默认选中第一条数据
                    }

                    if (this.orderId) {
                        this.defaultSelectedKeys = [this.orderId];//保存过后默认选择这个一条
                    }
                    this.listData = records;

                    this.typsTreeData[0].children.forEach(item => {
                        item.children = this.listData.filter((res) => { return res.bomGroupId == item.id });
                    });
                    // this.typsTreeData[0].children.forEach(item => {
                    //     if (item.key == 930413) {
                    //         item.children.push(...this.listData.filter((res) => { return !res.bomGroupId || res.bomGroupId == 930413 }));
                    //     }
                    // });


                    console.log(this.typsTreeData);




                    //如果没有orderId表示是第一次进入页面
                    if (!this.orderId) {
                        this.mouseIndex = records[0].key;
                        this.orderId = records[0].id;
                        this.voucherState = records[0].voucherState;
                        this.nowRecord = records[0];
                        this.getDetails(records[0]);
                    }

                    if (this.orderId) {
                        this.getDetails({ id: this.orderId });
                    }
                }
            }).catch(error => { });
        },
        //保存
        submit () {
            this.dataJson.orderDetailList = this.dataSource.filter(item => { return item.inventoryId });

            this.dataJson.reviewerDate = null;
            this.dataJson.reviewerUserId = null;
            this.dataJson.reviewerUserName = null;

            if (this.dataJson.inventoryCode == '' || this.dataJson.inventoryCode == null) {
                this.$message.warning('母件编码必须填写')
                return;
            }
            if (this.dataJson.inventoryName == '' || this.dataJson.inventoryName == null) {
                this.$message.warning('母件名称必须填写')
                return;
            }

            if (this.dataJson.bomGroupId == '' || this.dataJson.bomGroupId == null) {
                this.$message.warning('分组必须选择');
                return;
            }

            if (this.dataJson.processRouteName == '' || this.dataJson.processRouteName == null) {
                this.$message.warning('工艺路线必须选择')
                return;
            }

            if (this.dataJson.finishProductRate == '' || this.dataJson.inventoryName == null) {
                this.$message.warning('成品率必须填写')
                return;
            }

            let reg = /^\d+(?:\.\d{0,4})?/;
            if (!reg.test(this.dataJson.finishProductRate) || this.dataJson.finishProductRate < 0 || this.dataJson.finishProductRate > 100) {
                this.$message.warning('成品率必须大于0小于100的整数或者4位小数')
                return;
            }

            if (this.dataJson.versionCode == '' || this.dataJson.versionCode == null) {
                this.$message.warning('版本号不能为空')
                return;
            }
            if (JSON.stringify(this.dataJson.orderDetailList) == '[]') {
                this.$message.warning('母件明细不能为空')
                return;
            }
            let detais = this.dataJson.orderDetailList;
            for (let i = 0; i < detais.length; i++) {
                if (!detais[i].requireQuantity) {
                    this.$message.warning('主计量数量必须填写')
                    return;
                }
                if (!reg.test(detais[i].requireQuantity)) {
                    this.$message.warning('主计量数量填写错误')
                    return;
                }

                if (!detais[i].supplyType) {
                    this.$message.warning('供应类型必须选择')
                    return;
                }

                if (!detais[i].deliveryMethod) {
                    this.$message.warning('发料方式必须选择')
                    return;
                }
                if (!detais[i].lossRate) {
                    detais[i].lossRate = '0.00';
                } else {
                    if (!reg.test(detais[i].lossRate)) {
                        this.$message.warning('子件损耗率必须是两位小数');
                        return;
                    }
                    if (detais[i].lossRate > 100) {
                        this.$message.warning('子件损耗率不能超过100%');
                        return;
                    }
                    if (detais[i].lossRate < 0) {
                        this.$message.warning('子件损耗率不能小于0');
                        return;
                    }
                }
            }



            this.dataJson.createDate = '';
            this.dataJson.updateDate = '';

            let requestData = this.dataJson;
            save(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');

                    // if (!this.orderId) {
                    //     let tableBody = document.getElementById('route_tb').getElementsByClassName('ant-table-body');
                    //     setTimeout(() => {
                    //         tableBody[0].scrollTop = tableBody[0].scrollHeight;
                    //     }, 200)
                    // }
                    this.orderId = response.data;
                    this.mouseIndex = response.data;
                    this.voucherState = 0;
                    // this.getList();
                    this.getBomGroupList();
                    // this.getDetails({ id: response.data })

                } else {
                    this.$message.error(response.message);
                }
            }).catch((e) => {
                // this.isSaveRun = true;
            })
        },
        removeData () {
            //删除
            // if (this.selectedRowKeys.length != 1) {
            //     this.$message.warning('请选择一条数据');
            //     return;
            // }
            if (this.orderId == null || this.orderId == '') {
                this.$message.warning('请选择一条数据');
                return;
            }

            let _this = this;
            this.$confirm({
                title: `是否确认删除物料清单 "${_this.nowRecord.inventoryName}"`,
                content: "",
                onOk () {
                    remove({ id: _this.nowRecord.id }).then(response => {
                        if (response.code === 200) {
                            _this.$message.success('删除成功');
                            _this.selectedRowKeys = [];
                            _this.selectedData = [];
                            _this.newProcess();
                            _this.getList();
                            document.getElementById('route_tb').getElementsByClassName('ant-table-body')[0].scrollTop = 0;
                        } else {
                            _this.$message.error(response.message);
                        }
                    }).catch((e) => {
                    })
                },
                onCancel () { }
            });
        },
        handlInputArchives (type, ref) {
            this.styleProcess = null;
            this.styleOffice = null;

            let w = document.body.clientWidth;//当前可视窗口宽度
            this.maskArchives = true;

            if (w < 1600) {
                this.inventoryDomTop = 240;
            } else {
                this.inventoryDomTop = 195;
            }
        },
        closeArchives () {
            this.maskArchives = false;
        },
        checkArchives (data) {
            this.maskArchives = false;
            console.log(data);
            //返回值处理
            this.dataJson.inventoryId = data[0][0].id;
            this.dataJson.inventoryCode = data[0][0].inventoryCode;
            this.dataJson.inventoryName = data[0][0].inventoryName;
            this.dataJson.specification = data[0][0].inventorySpecification;
            this.dataJson.unitId = data[0][0].unitId ? data[0][0].unitId : data[0][0].unitGroupId;
            this.dataJson.unitName = data[0][0].unitName ? data[0][0].unitName : data[0][0].unitGroupName;
        },
        rowClassName (record, index) {
            return this.mouseIndex == record.key ? 'hoverRowStyl' : '';
        },
        handleArchiveChange (t) {
            //物料编码搜索
            if (t == 1) {
                this.inputVal = this.dataJson.inventoryCode;
            } else if (t == 2) {
                this.inputVal = this.dataJson.inventoryName;
            }
            this.$refs.searchArchivesRef.inputVal = this.inputVal;
            this.$refs.searchArchivesRef.getData(1);
        },
        onSelectChange (keys, data) {
            this.selectedRowKeys = keys;
            this.selectedData = data;
            console.log(keys, data)
        },
        getDetails (dd) {
            let record = JSON.parse(JSON.stringify(dd));
            this.editMask = true;
            let requestData = {
                bomId: record.id
            }
            details(requestData).then(response => {
                if (response.code === 200) {

                    //修改表格的处理
                    let newDataJson = this.listData.filter(item => item.id == record.id);
                    this.dataJson = JSON.parse(JSON.stringify(newDataJson[0]));;

                    this.dataSource = JSON.parse(JSON.stringify(response.data));

                    if (this.dataSource.length < this.dataSourceNumber) {
                        for (let i = 0; i < this.dataSourceNumber - response.data.length; i++) {
                            this.dataSource.push({})
                        }
                    }

                    //查看表格的处理
                    let backData = response.data;
                    for (let i = 0; i < backData.length; i++) {
                        if (backData[i].bomId != null) {
                            backData[i].children = [];
                        }
                        backData[i].key = backData[i].id;
                    }
                    this.innerData = backData;

                    this.reload();
                } else {
                    this.$message.error(response.message);
                }
            }).catch((e) => { })
        },
        editClick () {
            this.editMask = false;
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            examine(requestData).then((response) => {
                if (response.code === 200) {
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.getList();
                        this.voucherState = 1;
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.getList();
                        this.voucherState = 0;
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        expandChange (expanded, record) {
            if (record.children.length > 0) return false;
            //table展开
            details({ "bomId": record.bomId }).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    data.forEach(item => {
                        if (item.bomId) {
                            item.children = [];
                        }
                        item.key = item.id;
                    });

                    // this.childrenData = data;//子集数据
                    // this.recordId = record.bomId;//当前点击展开的bomId
                    record.children = data;
                    // this.nextArray(this.innerData);
                } else {
                    this.$message.error(response.message);
                }
            }).catch((e) => { })
        },
        nextArray (array) {
            for (const i in array) {
                let data = array[i];
                if (data.children) {
                    if (data.bomId == this.recordId) {
                        data.children = this.childrenData;
                    }
                    this.nextArray(data.children);
                }
            }
        },
        searchGroup (type) {
            //搜索组件的显示
            if (type == 1) {
                this.$nextTick(() => {
                    this.$refs.processSearch.showModal();
                    this.styleProcess = { "position": "relative", "z-index": 75 };
                    this.styleOffice = { "position": "relative", "z-index": 50 };
                })
            } else {
                //延迟请求
                this.$refs.processSearch.inputSearch();
            }
        },
        searchBackData (record) {
            console.log(record);
            this.$refs.processSearch.closeSearch();
            if (record.codesName == "office") {
                this.dataJson.officeId = record.id;
                this.dataJson.officeName = record.officeName;
            } else if (record.codesName == "processRoute") {
                // this.dataJson.processRouteId = record.id;
                // this.dataJson.processRouteName = record.name;
                this.$set(this.dataJson, 'processRouteName', record.name)
                this.$set(this.dataJson, 'processRouteId', record.id)
            }
        },
        choiceAddData (index, record) {
            console.log(index);
            console.log(record);
            //物料多选
            let newData = [...record];
            console.log(newData, this.dataSource)
            for (let i = 0; i < newData.length; i++) {
                let newDetails = {};
                newDetails['inventoryCode'] = newData[i].inventoryCode;//物料编码
                newDetails['inventoryId'] = newData[i].id;//物料名称
                newDetails['inventoryName'] = newData[i].inventoryName;//物料名称
                newDetails['specification'] = newData[i].inventorySpecification;//规格型号
                // newDetails['unitId'] = newData[i].unitId ? newData[i].unitId : newData[i].unitGroupId;//计量单位
                // newDetails['unitName'] = newData[i].unitName ? newData[i].unitName : newData[i].unitGroupName;//计量单位名称


                if (newData[i].unitId) {//单计量
                    newDetails['unitId'] = newData[i].unitId;
                    newDetails['unitName'] = newData[i].unitName;

                    //主计量
                    newDetails['baseUnit'] = newData[i].unitId;
                    newDetails['baseUnitName'] = newData[i].unitName;
                }

                if (newData[i].unitGroupId) {//多计量
                    newDetails['unitGroupId'] = newData[i].unitGroupId;
                    newDetails['baseUnit'] = newData[i].mainUnit;
                    newDetails['baseUnitName'] = newData[i].mainUnitName;


                    //辅助计量数据
                    this.unitsAssistSelect = [];
                    this.unitsDataDetails.forEach((element, index) => {
                        if (element.unitGroupId == newData[i].unitGroupId && !element.isMainUnit) {//&& !element.isMainUnit
                            this.unitsAssistSelect.push(element);
                        }
                    });

                    //辅助计量设置默认值
                    this.unitsAssistSelect.forEach(item => {
                        if (newData[i].proUnit == item.id) {//生产常用单位
                            newDetails['subUnit'] = item.id;//辅计量
                            newDetails['subUnitName'] = item.name;//辅计量名称
                            newDetails['unitExchangeRate'] = item.changeRate;//换算率
                        }
                    });

                    console.log('辅助计量组：', this.unitsAssistSelect, this.unitsDataDetails);
                }

                newDetails['lossRate'] = '0.00';

                if (newData.length == 1) {
                    this.dataSource.splice(index + i, 1, newDetails);
                } else {
                    this.dataSource.splice(index + i, 0, newDetails);
                }
            }
            this.reload();
        },
        handleSearch (key, confirm, col) {
            //table搜索
            confirm();
            console.log(key, confirm, col)
            this.searchInventoryCode = key[0];

            let searchText = { 'searchKey': this.searchInventoryCode }
            this.getList(searchText)
        },
        handleReset (clearFilters) {
            clearFilters();
            this.searchInventoryCode = '';
            this.getList()
        },
        copy () {
            //复制

            this.editMask = false;
            this.orderId = null;
            this.mouseIndex = null;
            this.dataJson.id = null;
            this.dataJson.voucherState = 0;
            this.dataSource.forEach(item => {
                item.id = null;
            });
            this.voucherState = 0;
            this.$message.success('复制成功，请修改后保存数据！');
        },
        onTreeSearchChange (e) {
            if (this.setTime) {
                clearTimeout(this.setTime)
            }
            this.setTime = setTimeout(() => {
                let { listData } = this;
                const value = e.target.value;
                listData.forEach(item => {
                    if (item.showname.indexOf(value) > -1) {
                        item.class = '';
                    } else {
                        item.class = 'hideBomNode';
                    }
                });
                this.reloadTree();
            }, 400)

        },
    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .credentials-bom-wrapper-bb {
        padding: 12px 10px 0;
        height: auto;
        overflow-y: auto;
        font-size: 14px;
        .ant-form-item {
            margin: 0;
        }
        .mask-archives {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            // background: rgba(220, 53, 69, 0.5);
            background: rgba(0, 0, 0, 0);
            z-index: 2;
        }
        .ant-table-tbody > tr > td {
            cursor: pointer;
        }
        .hoverRowStyl {
            background-color: rgba(24, 144, 255, 0.2);
            td {
                color: #222;
            }
        }
        .ant-table colgroup > col.ant-table-selection-col {
            width: 30px;
        }
        .edit-mask-route {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 800;
            background: rgba(255, 255, 255, 0.1);
        }
        .inner-table {
            margin: 0 !important;
        }

        .look-table {
            .ant-table-body {
                min-height: 300px;
            }
        }

        .order-dynamic-form-wrapper {
            label:not(.form-check-label):not(.custom-file-label) {
                font-weight: normal;
            }
            .ant-form-item-label,
            .ant-form-item-control {
                line-height: 32px;
            }
        }

        .atable-edit {
            .ant-table-tbody > tr > td {
                padding: 0px !important;
            }
        }

        .drag-line-top td {
            border-top: 1px dashed #1890ff;
        }

        .drag-line-bottom td {
            border-bottom: 1px dashed #1890ff !important;
        }
        .position-zindex-1 {
            position: relative;
            z-index: 71;
        }

        .ant-select-selection--single {
            height: 28px;
        }
        .ant-tree-title {
            max-width: 500px !important;
        }
    }
    .tabbl-bom {
        padding: 6px;
        .ant-table-scroll {
            height: 450px !important;
        }
        .ant-table-wrapper .ant-table-pagination {
            text-align: right !important;
        }
    }
    .bom-tree-wrapper {
        height: 560px;
        border-right: 1px solid #ccc;
        .tree-box {
            overflow-y: auto;
            width:auto;
        }
    }
    #editBom_tb,
    #lookBom_tb {
        margin: 8px 0;
    }
    .hideBomNode {
        display: none;
    }
</style>